from langchain.memory import ConversationBufferMemory
from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_openai import OpenAI
from langchain.chains import LLMChain

# 1. 记忆组件：自动维护 List[BaseMessage]
memory = ConversationBufferMemory(
    memory_key="history",      # 下面占位符要用同名
    return_messages=True       # 关键！直接返回 Message 对象
)

# 2. 模板：system + 历史占位符 + 最新人类问题
prompt = ChatPromptTemplate.from_messages([
    ("system", "你是贴心助手，会记住用户名字。"),
    MessagesPlaceholder(variable_name="history"),  # ← 视频核心
    ("human", "{input}")
])

# 3. 大模型 & 链
llm = OpenAI(
    max_retries=1,
    max_tokens=1024,
    temperature=0,
    openai_api_key="sk-rgymzddvnnrgwawnkevkdzlxkxfvhbviqgibbfgpvsyoqtur",
    openai_api_base="https://api.siliconflow.cn/v1",
    model="deepseek-ai/DeepSeek-R1-0528-Qwen3-8B"
)

chain = LLMChain(llm=llm, prompt=prompt, memory=memory)

# 4. 跑两轮
print(chain.invoke("我叫张三"))        # -> 你好张三！
print(chain.invoke("那我现在叫什么？"))  # -> 你叫张三呀